package com.agileboot.common.utils.file;

import org.springframework.lang.NonNull;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * MultipartFile工具类
 */
public class MultipartFileUtils {

    /**
     * 从字节数组创建MultipartFile
     */
    public static MultipartFile createMultipartFile(byte[] bytes, String fileName, String contentType) {
        final byte[] fileBytes = bytes != null ? bytes : new byte[0];
        return new MultipartFile() {
            @Override
            @NonNull
            public String getName() {
                return "file";
            }

            @Override
            public String getOriginalFilename() {
                return fileName;
            }

            @Override
            public String getContentType() {
                return contentType;
            }

            @Override
            public boolean isEmpty() {
                return fileBytes.length == 0;
            }

            @Override
            public long getSize() {
                return fileBytes.length;
            }

            @Override
            @NonNull
            public byte[] getBytes() throws IOException {
                return fileBytes;
            }

            @Override
            @NonNull
            public InputStream getInputStream() throws IOException {
                return new ByteArrayInputStream(fileBytes);
            }

            @Override
            public void transferTo(@NonNull File dest) throws IOException, IllegalStateException {
                throw new UnsupportedOperationException("transferTo not supported");
            }
        };
    }
}

